package cn.com.twoke.app.pin_dou_dou.core;

import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.status.ErrorStatus;
import lombok.Setter;

import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.awt.*;

public class JTextAreaAppender extends AppenderBase<ILoggingEvent> {
    private static JTextArea textArea;
    private static final int MAX_LINES = 1000;
    private Layout<ILoggingEvent> layout;
    @Setter
    private String pattern;

    public JTextAreaAppender() {
        // 设置默认模式
        this.pattern = "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n";
    }

    @Override
    public void start() {
        if (this.layout == null) {
            PatternLayout patternLayout = new PatternLayout();
            patternLayout.setPattern(pattern);
            patternLayout.setContext(getContext());
            patternLayout.start();
            this.layout = patternLayout;
        }
        super.start();
    }

    public static void setTextArea(JTextArea textArea) {
        JTextAreaAppender.textArea = textArea;
        if (textArea != null) {
            textArea.setEditable(false);
            textArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
        }
    }

    @Override
    protected void append(ILoggingEvent event) {
        if (textArea == null) {
            addStatus(new ErrorStatus("JTextArea is not set for JTextAreaAppender.", this));
            return;
        }

        if (layout == null) {
            addStatus(new ErrorStatus("Layout is not set for JTextAreaAppender.", this));
            return;
        }

        String formattedMessage = layout.doLayout(event);

        SwingUtilities.invokeLater(() -> {
            try {
                Document doc = textArea.getDocument();
                doc.insertString(doc.getLength(), formattedMessage, null);
                
                // 限制行数
                limitLineCount();
                
                // 自动滚动到底部
                textArea.setCaretPosition(doc.getLength());
            } catch (BadLocationException e) {
                System.err.println("写入JTextArea失败: " + e.getMessage());
            }
        });
    }

    private void limitLineCount() {
        int lineCount = textArea.getLineCount();
        if (lineCount > MAX_LINES) {
            try {
                int linesToRemove = lineCount - MAX_LINES / 2; // 保留一半的行数
                int startOffset = textArea.getLineStartOffset(linesToRemove);
                int endOffset = textArea.getLineEndOffset(linesToRemove);
                textArea.getDocument().remove(0, endOffset);
            } catch (Exception e) {
                // 忽略异常，避免影响日志输出
            }
        }
    }
}